package com.sunzm.dynamic_rule.utils;

import com.sunzm.dynamic_rule.pojo.RuleAtomicParam;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 行为次数类条件查询sql拼接工具
 */
public class ClickhouseCountQuerySqlUtil {
    public static String getSql(String deviceId, RuleAtomicParam atomicParam) {

        String templet1 =
                " SELECT " + System.lineSeparator() +
                        "  deviceId,COUNT() AS cnt " + System.lineSeparator() +
                        " FROM event_detail " + System.lineSeparator() +
                        " WHERE deviceId = '" + deviceId + "' " + System.lineSeparator() +
                        " AND eventId = '" + atomicParam.getEventId() + "' " + System.lineSeparator() +
                        " AND timeStamp >= " + atomicParam.getRangeStart() +
                        " AND timeStamp <=" + atomicParam.getRangeEnd() + System.lineSeparator();


        String templet3 = " GROUP BY deviceId";


        HashMap<String, String> properties = atomicParam.getProperties();
        Set<Map.Entry<String, String>> entries = properties.entrySet();


        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : entries) {
            sb.append(" AND properties['").append(entry.getKey()).append("'] = '")
                    .append(entry.getValue()).append("'")
                    .append(System.lineSeparator());
        }

        return templet1 + sb.toString() + templet3;
    }

    public static void main(String[] args) {
        RuleAtomicParam ruleAtomicParam = new RuleAtomicParam();
        ruleAtomicParam.setEventId("collect");
        HashMap<String, String> props = new HashMap<>();
        props.put("productId", "7");
        props.put("pageId", "7");
        ruleAtomicParam.setProperties(props);
        ruleAtomicParam.setRangeStart(1625912620006L);
        ruleAtomicParam.setRangeEnd(1625912625119L);

        String sql = getSql("0061", ruleAtomicParam);
        System.out.println(sql);
    }
}
